<?php

App::uses('AppModel', 'Model');

class Product extends AppModel{
    
	public $belongsTo = array('ProductType');
	
	public $hasMany = array(
		'ProductPrice' => array(
			'dependent'	=> true,
			'order'		=> 'ProductPrice.effective_date DESC, ProductPrice.id DESC'
		),
		'ProductClients'
	);
	
	public $validate = array(
		'name' => array(
			'rule' => 'notEmpty',
			'allowEmpty' => false,
			'message' => 'Morate uneti naziv proizvoda'
		)
	);
	
	public $order = "Product.name";
	
	public function getOptions() {
		$products = $this->find('list', array(
			'fields' => array('Product.id', 'Product.name', 'ProductType.name'),
			'joins' => array(
				array(
					'table' => 'product_types',
					'alias' => 'ProductType',
					'conditions' => array('Product.product_type_id=ProductType.id')
				)
			),
			"order" => "ProductType.name, Product.name"
		));
		
		return $products;
	}
	
	public function getPricelists() {
	    $dates = $this->ProductPrice->find('all', array(
	        'fields' => array('DISTINCT effective_date'),
	        'order' => 'effective_date DESC'
	    ));
	    
	    return Set::extract($dates, '{n}.ProductPrice');
	}
	
	public function getPricelist($date) {
	    $data = $this->ProductPrice->findAllByEffectiveDate($date);
	    $data = Set::combine($data, '{n}.Product.id', '{n}');
	    
	    return $data;
	}
	
	public function getAllGroupedByType() {
	    $group = array();
	    $products = $this->find('all', array(
            'fields' => array('Product.*', 'ProductType.*'),
            'recursive' => 0,
            'order' => array('ProductType.name', 'Product.name')
        ));
	    foreach($products as $row) {
	        $type = $row['ProductType']['name'];
	        if (empty($group[$type])) {
	            $group[$type] = array();
	        }
	        
	        $group[$type][] = $row;
	    }
	    
	    return $group;
	}
}

?>